<script setup lang="ts">
import { add, update,deptTypeList } from '@/api/system/dept';
import { useForm } from '@/hooks/useForm';
import { watch, ref, computed, onMounted, reactive, toRefs } from 'vue';
import { getDeptTree } from '@/api/system/dept';
import { notify } from '@/utils/element';
import { SysDeptType } from '@/types/system';

//定义自定义事件
const emit = defineEmits(['refresh']);

const initData = {status: '0'};

const state = reactive({
    title: '新增',      //新增 || 编辑
    type: 'add' as FormType,
    visible: false,
    loading: false,
    formData: {
        status: '0',
    } as SysDeptType,
})

const { title, type , visible , loading , formData } = {...toRefs(state)};

defineExpose({
    open,
});

function open(type: FormType, title: string, data= {} as any) {
    state.type = type;
    state.title = title;
    //合并初始数据，深度拷贝，不然会影响原数据
    state.formData = JSON.parse(JSON.stringify({ ...initData, ...data }));
    state.visible = true;
    getTreeData();
}

onMounted(() => {
    getTreeData();
    loadRoleOptions()
});

const disabled = computed(() => type.value ==='edit');

const roleOptions = ref([]);

let deptList: any[] = [];
let deptTypeOptions = ref([])

async function getTreeData(){
  const { data } = await getDeptTree();
  deptList = data;
}

async function loadRoleOptions() {
  try {
    loading.value = true;
  // @ts-ignore
    const { data } = await deptTypeList();
    if (data && data.length > 0) {
        deptTypeOptions.value = data.map((item: any) => ({
        value: item.id,
        label: item.name,
      }));
    } else {
        deptTypeOptions.value = [];
    }
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

const formRef = ref();
function submitForm() {
    formRef.value?.validate((valid: boolean) => {
        if(!valid) return;
        //校验通过
       //调用接口，提交数据
        submitData();

    });
}

function close() {
    if(state.loading) return;
    formRef.value?.resetFields();
    state.visible = false;
}

async function submitData() {
    try {
        state.loading = true;
        let res: any = {};
        if(state.type === 'edit') {
            res = await update(state.formData);
        }else {
            res = await add(state.formData);
        }
        state.loading = false;
        if(res.code !== 200) return;
        notify('操作成功！', {type: 'success'});
        //关闭窗口
        close();
        //触发父组件重新加载数据
        emit('refresh');
    } catch (error) {
    } finally {
        state.loading = false;
    }
}
</script>

<template>
  <el-drawer :title="title+'部门'"  v-model="visible" :before-close="close" direction="rtl" size="650px">
        <el-form v-loading="loading" ref="formRef" :model="formData" label-width="85px" label-position="right" status-icon label-suffix=":">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="上级部门" prop="parentId">
                        <!--级联选择器-->
                        <el-cascader v-model="formData.parentId"
                        :options="deptList"
                        :props="{checkStrictly: true, emitPath: false, value: 'id', label: 'label'}"
                        clearable
                        class="w100"/>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="部门名称" prop="deptName"  :rules="{required: true,message:'请输入部门名称',trigger:'blur'}">
                        <el-input v-model.trim="formData.deptName" placeholder="请输入部门名称" maxlength="30" show-word-limit clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="组织分类" prop="deptType"  :rules="{required: true,message:'请输入组织分类',trigger:'blur'}">
                        <el-select-v2
                            v-model="formData.deptType"
                            :options="deptTypeOptions"
                            placeholder="请选择组织分类"
                            style="width: 100%"
                            clearable
                            />
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="显示排序" prop="orderNum"  :rules="{required: true,message:'请输入排序号',trigger:'blur'}">
                        <el-input-number v-model="formData.orderNum" :min="1" :max="9999"  placeholder="请输入排序号" class="w100" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="负责人" prop="leader">
                        <el-input v-model.trim="formData.leader" placeholder="请输入负责人" :disabled="disabled" maxlength="30" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="联系电话" prop="phone">
                        <el-input v-model.trim="formData.phone" placeholder="请输入手机号码" maxlength="20" show-word-limit clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="电子邮箱" prop="email">
                        <el-input v-model.trim="formData.email" placeholder="请输入电子邮箱" maxlength="30" show-word-limit clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="部门状态" prop="status">
                        <el-radio-group v-model="formData.status">
                            <el-radio value="0" border>正常</el-radio>
                            <el-radio value="1" border>停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-row justify="center" class="mt10">
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
        </el-row>
    </el-drawer>
</template>

<style scoped>

</style>
